package postman;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Yan on 2018/4/3.
 */
public class ExportPostManApiUtil {

    public static String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long fileLength = file.length();
        byte[] fileContent = new byte[fileLength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(fileContent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(fileContent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
//        readFile("C:\\Users\\Yan\\Desktop\\api\\b.json");
//        readFile("C:\\Users\\Yan\\Desktop\\api\\c.json");
//        readFile("C:\\Users\\Yan\\Desktop\\api\\d.json");
//        readFile("C:\\Users\\Yan\\Desktop\\api\\e.json");
//        readFile("C:\\Users\\Yan\\Desktop\\api\\f.json");
        readFile("F:\\sy_system.postman_collection.json");
    }

    /**
     * 解析postman 导出的Json数据
     *
     * @param path
     */
    private static void readFile(String path) {
        String file = readToString(path);
        JSONObject allData = JSONObject.fromObject(file);
        String title = allData.getString("name");
        String requests = allData.getString("requests");
        String folders = allData.getString("folders");

        List<Folder> folderList = new ArrayList<Folder>();
        JSONArray foldersJson = JSONArray.fromObject(folders);
        for (Object o : foldersJson) {
            JSONObject jo = (JSONObject) o;
            Folder folder = new Folder();
            folder.setName(jo.getString("name"));
            folder.setOrder(jo.getString("order"));
            folderList.add(folder);
        }


        JSONArray reqList = JSONArray.fromObject(requests);

        List<Api> apiList = new ArrayList<>();

        for (Object o : reqList) {
            JSONObject jo = (JSONObject) o;
            Api api = new Api();
            api.setId(jo.getString("id"));
            api.setName(jo.getString("name"));
            api.setUrl(jo.getString("url"));
            api.setMethod(jo.getString("method"));

            if (!jo.getString("data").equals("null")) {
                JSONArray dataArr = JSONArray.fromObject(jo.getString("data"));
                List<Data> dataList = new ArrayList<>();
                if (dataArr.size() > 0) {
                    for (Object d : dataArr) {
                        JSONObject jsonData = (JSONObject) d;
                        Data data = new Data();
                        data.setKey(jsonData.getString("key"));
                        data.setType(jsonData.getString("type"));
                        data.setEnabled(jsonData.getBoolean("enabled"));
                        if (jsonData.containsKey("description")) {
                            data.setDescription(jsonData.getString("description"));
                        }
                        data.setValue(jsonData.getString("value"));
                        dataList.add(data);
                    }
                }
                api.setData(dataList);
            }
            apiList.add(api);
        }
        for (Api api : apiList) {
            for (Folder folder : folderList) {
                if (folder.getOrder().indexOf(api.getId()) >= 0) {
                    folder.getApiList().add(api);
                }
            }
        }
        writeToHtml(title, folderList);
    }

    /**
     * 数据拼成html
     *
     * @param title
     * @param folderList
     */
    private static void writeToHtml(String title, List<Folder> folderList) {

        StringBuffer buffer = new StringBuffer();
        buffer.append("<style>" +
                "ul{margin-left:30px;}" +
                "li{left:20px;list-style-type:none;padding-bottom:10px;}table{margin-top:10px;}" +
                "td{height:40px;line-height:40px; Word-break: break-all;}" +
                "h3{left:20px;padding-bottom:10px;position:relative;}h4{left:40px;padding-bottom:10px;position:relative;}" +
                "td > span{display:inline-block;margin-left:20px;}" +
                ".tdspan1{width:120}.tdspan2{width:110}.tdspan3{width:100}.tdspan4{width:240}.tdspan5{width:400}" +
                "</style>");
        buffer.append("<h2>" + title + "</h2>");
        buffer.append("<br/>");
        int i = 0;
        for (Folder folder : folderList) {
            i++;
            List<Api> apiList = folder.getApiList();
            buffer.append("<h3 style='margin:1px 0 1px 0'>" + i + ". 模块名称：" + folder.getName() + "</h3>");
            int j = 0;
            for (Api api : apiList) {
                j++;
                buffer.append("<h4 style='margin:1px 0 1px 0'>" + i + "." + j + " 接口名称：" + api.getName() + "</h4>");
                buffer.append("<ul>");


                buffer.append("<li style='margin:1px 0 1px 0'>接口地址：" + api.getUrl() + "</li>");
                buffer.append("<li style='margin:1px 0 1px 0'>请求方式：" + api.getMethod() + "</li>");

                List<Data> dataList = api.getData();
                if (null != dataList && dataList.size() > 0) {
                    buffer.append("<li><div> <style='margin:1px 0 1px 0'>请求参数：</div>");


                    buffer.append("<div><table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">");
                    buffer.append("<tr>");
                    buffer.append("<td>参数名</td><td>参数类型</td><td>是否必填</td><td>示例值</td><td>描述</td>");
                    buffer.append("</tr>");
                    for (Data data : dataList) {
                        buffer.append("<tr>");
                        buffer.append("<td><span class='tdspan1'>" + data.getKey() + "</span></td>" +
                                "<td><span class='tdspan2'>" + data.getType() + "</span></td>" +
                                "<td><span class='tdspan3'>" + data.getEnabled() + "</span></td>");
                        String exampleData = data.getValue();
                        int len = exampleData.length();
                        buffer.append("<td><span class='tdspan4'>" + exampleData + "</span></td>");
                        buffer.append("<td><span class='tdspan5'>" + data.getDescription() + "</span></td>");
                        buffer.append("</tr>");
                    }
                    buffer.append("</table></div>");
                    buffer.append("</li>");
                }
                List<Example> exampleList = api.getExampleList();
                if(null != exampleList && exampleList.size() > 0){
                    for(Example example:exampleList) {
                        buffer.append("<li><div> <style='margin:1px 0 1px 0'>请求参数：</div>");

                        buffer.append("</table></div>");
                        buffer.append("</li>");
                    }
                }
                buffer.append("</ul>");


            }

        }
        System.out.println(buffer.toString());
        File file = new File("f://1.html");
        FileWriter fw = null;
        try {
            fw = new FileWriter(file);
            fw.write(buffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.flush();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
